import cv2

def preprocess_image(image_path):
    # Load the image in grayscale mode
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    # Apply median blur to reduce noise while preserving edges
    denoised_image = cv2.medianBlur(image, 5)  # Kernel size of 5
    # Apply Gaussian blur to smooth the image (if needed after denoising)
    blurred_image = cv2.GaussianBlur(denoised_image, (5, 5), 0)
    # Apply adaptive thresholding to enhance text contrast
    thresholded_image = cv2.adaptiveThreshold(blurred_image, 
                                              255, 
                                              cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 
                                              cv2.THRESH_BINARY, 
                                              11, 
                                              2)
    # Display the results (optional)
    cv2.imshow("Original Image", image)
    # cv2.imshow("Denoised Image", denoised_image)
    cv2.imshow("Processed Image", thresholded_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return thresholded_image

if __name__ == '__main__':
    image_path = 'images.jpeg'  # Replace with your image path
    processed_image = preprocess_image(image_path)
